<template>
  <div>
    <div :id="id"></div>
  </div>
</template>
<script>
  import DataSet from '@antv/data-set'
  import { Chart, registerShape, Util } from '@antv/g2'
  function getTextAttrs(cfg) {
    // console.log(cfg)
    return {
      ...cfg.defaultStyle,
      ...cfg.style,
      fontSize: cfg.data.size,
      text: cfg.data.text,
      textAlign: 'center',
      fontFamily: cfg.data.font,
      fill: cfg.color,
      textBaseline: 'Alphabetic',
    }
  }
  // 给point注册一个词云的shape
  registerShape('point', 'cloud', {
    draw(cfg, container) {
      const attrs = getTextAttrs(cfg)
      const textShape = container.addShape('text', {
        attrs: {
          ...attrs,
          x: cfg.x,
          y: cfg.y,
        },
      })
      if (cfg.data.rotate) {
        Util.rotate(textShape, (cfg.data.rotate * Math.PI) / 180)
      }

      return textShape
    },
  })
  export default {
    data() {
      return {
        chart: {},
      }
    },
    props: {
      chartData: {
        type: Array,
      },
      id: {
        type: String,
      },
      height: {
        type: Number,
      },
    },
    mounted() {
      this.Initialization()
    },
    watch: {
      chartData(val) {
        // debugger
        // this.chart.changeData(val)
        this.Initialization()
      },
    },
    methods: {
      Initialization() {
        const dv = new DataSet.View().source(this.chartData)
        const range = dv.range('count')
        const min = range[0]
        const max = range[1]
        dv.transform({
          type: 'tag-cloud',
          fields: ['item', 'count'],
          size: [600, 500],
          font: 'Verdana',
          padding: 0,
          timeInterval: 5000, // max execute time
          rotate() {
            let random = ~~(Math.random() * 4) % 4
            if (random === 2) {
              random = 0
            }
            return random * 90 // 0, 90, 270
          },
          fontSize(d) {
            if (d.value) {
              return ((d.value - min) / (max - min)) * (80 - 24) + 24
            }
            return 0
          },
        })
        this.chart = new Chart({
          container: this.id,
          autoFit: false,
          width: 400,
          height: 360,
          padding: 0,
        })
        this.chart.data(dv.rows)
        this.chart.scale({
          x: { nice: false },
          y: { nice: false },
        })
        this.chart.legend(false)
        this.chart.axis(false)
        this.chart.tooltip({
          showTitle: false,
          showMarkers: true,
        })
        this.chart.coordinate().reflect()
        this.chart
          .point()
          .position('x*y')
          .color('text')
          .shape('cloud')
          .state({
            active: {
              style: {
                fillOpacity: 0.4,
              },
            },
          })
        this.chart.interaction('element-active')
        this.chart.render()
      },
    },
  }
</script>
